﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using schemas.microsoft.com.linqtosql.dbml.Item2007;

namespace LinqToDbmlRunner
{
	class Program
	{
		static int Main(string[] args)
		{
			try
			{
				if (args.Length < 2)
				{
					throw new Exception("Usage: xsdrunner.console scriptAssembly inputXmlFile outputXmlFile");
				}
				Assembly assembly = Assembly.LoadFrom(args[0]);
				List<System.Type> xsdScripts = new List<System.Type>(assembly.GetTypes().Where(type => typeof(LinqToDbmlScript).IsAssignableFrom(type)));
				xsdScripts.Sort(new Comparison<System.Type>((t1, t2) => t1.Name.CompareTo(t2.Name)));

				XRoot root = XRoot.Load(args[1]);
				foreach (var xsdScript in xsdScripts)
				{
					var xsdScriptInstance = (LinqToDbmlScript)Activator.CreateInstance(xsdScript);
					xsdScriptInstance.Apply(root);
				}
				root.Save(args[2]);
				return 0;
			}catch(Exception ex){
				WriteMessage(Assembly.GetExecutingAssembly().FullName, "", Category.error, "1", ex.ToString());
				return 1;
			}
		}
		enum Category{
			error, 
			warning
		}
		static void WriteMessage(string origin, string subcategory, Category category, string code, string text)
		{
			System.Console.WriteLine("{0} : {1} {2} {3} : {4}", origin, subcategory, category.ToString(), code, text);
		}

	}
}
